package br.com.manutencao.reports;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.com.manutencao.entities.Chamado;
import br.com.manutencao.entities.Maquina;
import br.com.manutencao.repositories.MaquinaRepository;

public class ReportService {
	
	private Maquina maquina;
	private Date dataInicial;
	private Date dataFinal;
	
	private EntityManager em;
	
	public ReportService() {
		em = Persistence.createEntityManagerFactory("jsf")
		.createEntityManager();
	}
	
	public Collection<ReportBean> getReport(Date dataInicial, Date dataFinal) {
		List<ReportBean> report = new ArrayList<ReportBean>();
		
		this.dataInicial = dataInicial;
		this.dataFinal = dataFinal;
		
		Collection<Maquina> maquinas = getMaquinas();
		
		for (Maquina maquinaItem : maquinas) {
			this.maquina = maquinaItem;
			
			ReportBean bean = new ReportBean();
			bean.setMaquina(maquina);
			bean.setChamados(filtraChamados());
			bean.setAbertura(dataInicial);
			bean.setAbertura(dataFinal);
			
			report.add(bean);
		}
		
		Collections.sort(report, new Comparator(){
			public int compare(Object o1, Object o2) {
                ReportBean bean1 = (ReportBean) o1;
                ReportBean bean2 = (ReportBean) o2;
               return bean1.getNumeroChamados().compareTo(bean1.getNumeroChamados());
            }
		});
		
		Collections.reverse(report);
		
		return report;
	}
	
	private Collection<Chamado> filtraChamados() {
		
		Query query = em.createNamedQuery("Chamado.filtro");
		query.setParameter("maquina", maquina);
		query.setParameter("data_inicial", dataInicial);
		query.setParameter("data_final", dataFinal);
		Collection<Chamado> chamados = query.getResultList();
		
		return chamados;
	}
	
	private Collection<Maquina> getMaquinas() {
		MaquinaRepository repo = new MaquinaRepository();
		Collection<Maquina> maquinas = repo.buscaTodos();
		repo = null;
		return maquinas;
	}

}
